package com.hongxun.design.sqlite.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.facebook.drawee.view.SimpleDraweeView;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.activitys.BaseActivity;
import com.hongxun.design.activitys.SetPointInformationActivity;
import com.hongxun.design.bean.Exploration;
import com.hongxun.design.bean.SetPointInfItemBean;
import com.hongxun.design.interfaces.HeadSecond;
import com.hongxun.design.interfaces.UpdateMap;
import com.hongxun.design.listeners.ListenerSet;
import com.hongxun.design.listeners.MyLocationListenner;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.SetTypeface;
import com.hongxun.design.mytools.ShardPreferencesTool;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.sqlite.bean.PointLaXian;
import com.hongxun.design.ui.MBaiduMap;
import com.hongxun.design.ui.headandbottonpanel.HeadSecondControlPanel;
import com.hongxun.design.utils.DataUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.imageutil.UriUtil;
import com.hongxun.design.utils.maputil.GeoCodeUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 拉线坐标获取
 */
public class EditPointLXLocaltionActivity extends BaseActivity implements HeadSecond,
        OnGetGeoCoderResultListener, UpdateMap {
    private BaiduMap mBaiduMap;
    private MapView mMapView;
    private MBaiduMap baidumapstyle;

    private LatLng currentPt, currentPt0;//经纬
    private double altitude;//海拔
    private TextView words, tv_AddLx;//显示地名
    private String finishAdress = "";
    private GeoCodeUtil geoCodeUtil;
    private List<Exploration> point;
    private List<PointLaXian> laXianList;
    private Map<String, Polyline> map;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_editpointlxlocation);
        findBar();
        findView_Map();
        addPoint();
        initialization_Map();
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mMapView != null) {
            mMapView.onResume();
        }
        MyApp.activity = this;
        mActivity = this;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mMapView != null) {
            mMapView.onPause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMapView != null) {
            try {
                geoCodeUtil.onDestroy();
                mBaiduMap.setMyLocationEnabled(false);
                mMapView.onDestroy();
                mMapView = null;
            } catch (Exception e) {
            }
        }
    }

    private void initData() {
        map = new HashMap<>();
        String laxian = ShardPreferencesTool.read(getApplicationContext(), MyApp.currExploration.getExploration_id(), "", 2);
        this.laXianList = JSON.parseArray(laxian, PointLaXian.class);
        if (laXianList != null) {
            for (PointLaXian laXian : laXianList) {
                setLaXianOnMap(laXian);
            }
        } else {
            laXianList = new ArrayList<>();
        }
    }

    //初始化加载数据
    private void setLaXianOnMap(PointLaXian laXian) {
        int zoom = (int) mBaiduMap.getMapStatus().zoom;
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.laxian);
        LatLng latLng = new LatLng(laXian.getLat(), laXian.getLng());
        OverlayOptions option = new MarkerOptions().position(latLng).zIndex(zoom)
                .icon(bitmap)
                .draggable(true)
                .anchor(0.5f, 1.0f);//取值范围：0.0f-1.0f
        Marker marker = (Marker) mBaiduMap.addOverlay(option);
        Bundle bundlesl = new Bundle();
        bundlesl.putParcelable("1", laXian);
        marker.setExtraInfo(bundlesl);

        List<LatLng> latLngs = new ArrayList<>();
        latLngs.add(currentPt0);
        latLngs.add(latLng);
        OverlayOptions ooPolyline = new PolylineOptions().width(5)
                .color(getResources().getColor(R.color.red))
                .points(latLngs)
                .dottedLine(true)
                .zIndex(zoom);
        Polyline mPolyline = (Polyline) mBaiduMap.addOverlay(ooPolyline);
        map.put(laXian.getLxname(), mPolyline);
//        Bundle bundlesm = new Bundle();
//        bundlesl.putSerializable("1", laXian);
//        mPolyline.setExtraInfo(bundlesl);

    }

    @Override
    public void findBar() {
        String name = "设置拉线位置：" + MyApp.currExploration.getNumber();
        HeadSecondControlPanel headsecond_layout = (HeadSecondControlPanel) findViewById(R.id.headsecond_layout);
        headsecond_layout.initHeadPanel(DataUtil.getsecondbean(MString.Save, View.VISIBLE, R.color.bar_right, ListenerSet.back,
                name, R.color.title, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
        headsecond_layout.setClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setReturnData();
            }
        });
    }

    private void setReturnData() {
        if (currentPt.longitude < 0 || currentPt.latitude < 0 || currentPt.longitude == 4.9E-324 || currentPt.latitude == 4.9E-324) {
            ToastShow.showShort(mActivity, "定位失败！");
            return;
        }
        double[] d = null;
        if (currentPt != null) {
            d = new double[]{currentPt.longitude, currentPt.latitude, altitude};
        }
        List<SetPointInfItemBean> data = SetPointInformationActivity.adapter.getData();
        for (SetPointInfItemBean datum : data) {
            if (datum.getName().contains("拉线")) {
                datum.setValue(laXianList.size() + "");
                datum.setNovalue("1");//判定输入框不能输入依据
                break;
            }
        }
        SetPointInformationActivity.adapter.notifyDataSetChanged();
        //new
        ShardPreferencesTool.save(getApplicationContext(), MyApp.currExploration.getExploration_id(), FastJsonUtil.beanToJson(laXianList), 2);
        finish();
    }

    /**
     * 地图控件
     */
    private void findView_Map() {
        words = (TextView) findViewById(R.id.words);
        words.setText("长按拖拽、单击选择删除");
        tv_AddLx = (TextView) findViewById(R.id.tv_add_eplx);
        SetTypeface.set(tv_AddLx, IconSourse.ADD);
        tv_AddLx.append(" 添加拉线");
        baidumapstyle = (MBaiduMap) findViewById(R.id.baidumapstyle);
        mMapView = baidumapstyle.getMapView();
        mBaiduMap = baidumapstyle.getBaiduMap();
        baidumapstyle.setPositionClick(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //重新定位
                inItLocation();
            }
        });

    }

    /**
     * 卫星图
     **/
    boolean isstylesatellite = false;

    public void ChangeSatellite(View v) {
        if (isstylesatellite) {
            isstylesatellite = false;
            ((SimpleDraweeView) v).setImageURI(UriUtil.getUri(MString.LOCALIMAGEHEAD + R.mipmap.style_satellite));
            mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        } else {
            isstylesatellite = true;
            ((SimpleDraweeView) v).setImageURI(UriUtil.getUri(MString.LOCALIMAGEHEAD + R.mipmap.style_map));
            mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
        }
    }

    /**
     * 地图初始化
     */
    private void initialization_Map() {
        geoCodeUtil = GeoCodeUtil.getInstence(this);
        mMapView.getMapLevel();
        if (MyApp.bdLocation == null) {
            inItLocation();
        } else {
            currentPt = new LatLng(MyApp.bdLocation.getLatitude(), MyApp.bdLocation.getLongitude());
            altitude = MyApp.bdLocation.getAltitude();
            updateMapState();
        }
        double lat;
        double lon;
        try {
            lat = Double.parseDouble(MyApp.currExploration.getLat());
            lon = Double.parseDouble(MyApp.currExploration.getLng());
        } catch (NumberFormatException e) {
            lat = MyApp.bdLocation.getLatitude();
            lon = MyApp.bdLocation.getLongitude();
        }
        currentPt = new LatLng(lat, lon);
        currentPt0 = new LatLng(lat, lon);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().target(currentPt).zoom(MyApp.zoom).build()));
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(currentPt));//将位置设为中心点

        initListener();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    ACCESS_COARSE_LOCATION);
        }
        if (!MyApp.NetWorkConnect) {
            ToastShow.showShort(this, "网络异常，请检查网络！");
        }
        LocationManager alm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (!alm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            ToastShow.showShort(this, "GPS未开启,请打开GPS！");
        }
    }

    private int READ_SYNC_SETTINGS = 100;
    private int ACCESS_COARSE_LOCATION = 101;
    private int ACCESS_FINE_LOCATION = 102;

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == READ_SYNC_SETTINGS) {
            ToastShow.showShort(this, "百度地图权限未打开，请到设置里面开启！");
        } else if (requestCode == ACCESS_COARSE_LOCATION) {
            ToastShow.showShort(this, "网络定位权限未打开，请到设置里面开启！");
        } else if (requestCode == ACCESS_FINE_LOCATION) {
            ToastShow.showShort(this, "GPS权限未开启，请到设置里面开启！");
        }
    }

    /**
     * 以下为地图相关方法*
     */
    private void inItLocation() {
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 定位初始化
        MyLocationListenner myListener = MyLocationListenner.getint(mMapView, this);
        myListener.setIsFirstLoc(true);
    }

    //点击监听
    private void initListener() {

        mBaiduMap.setOnMapTouchListener(new BaiduMap.OnMapTouchListener() {

            @Override
            public void onTouch(MotionEvent event) {

            }
        });

        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            public void onMapClick(LatLng point) {
            }

            public boolean onMapPoiClick(MapPoi poi) {
                return false;
            }
        });
        mBaiduMap.setOnMapLongClickListener(new BaiduMap.OnMapLongClickListener() {
            public void onMapLongClick(LatLng point) {
            }
        });
        mBaiduMap.setOnMapDoubleClickListener(new BaiduMap.OnMapDoubleClickListener() {
            public void onMapDoubleClick(LatLng point) {
            }
        });
        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            LatLng startLng, finishLng;

            public void onMapStatusChangeStart(MapStatus status) {
                startLng = status.target;
            }

            public void onMapStatusChangeFinish(MapStatus status) {
                finishLng = status.target;
                if (startLng.latitude != finishLng.latitude
                        || startLng.longitude != finishLng.longitude) {
                    currentPt = mBaiduMap.getMapStatus().bound.getCenter();
                    updateMapState(currentPt);
                }
            }

            public void onMapStatusChange(MapStatus status) {

            }
        })
        ;
        //new
        mBaiduMap.setOnMarkerDragListener(new BaiduMap.OnMarkerDragListener() {
            PointLaXian laXian;
            Marker marker0;
            int indexOf;
            Polyline polyline;

            @Override
            public void onMarkerDrag(Marker marker) {
                updateMapState();
            }

            @Override
            public void onMarkerDragEnd(Marker marker) {
                marker0.remove();
                polyline.remove();
                laXian.setLat(marker.getPosition().latitude);
                laXian.setLng(marker.getPosition().longitude);
                laXianList.set(indexOf, laXian);
                setLaXianOnMap(laXian);
            }

            @Override
            public void onMarkerDragStart(Marker marker) {
                marker0 = marker;
                laXian = marker.getExtraInfo().getParcelable("1");
                indexOf = laXianList.indexOf(laXian);
                polyline = map.get(laXian.getLxname());
                map.remove(laXian.getLxname());
            }
        });

        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(final Marker marker) {

                final PointLaXian laXian = marker.getExtraInfo().getParcelable("1");
                final Polyline polyline = map.get(laXian.getLxname());

                new AlertDialog.Builder(mActivity)
                        .setMessage("是否删除该拉线?")
                        .setNegativeButton("否", null)
                        .setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                laXianList.remove(laXian);
                                map.remove(laXian.getLxname());
                                marker.remove();
                                polyline.remove();
                                dialog.dismiss();
                            }
                        }).create().show();
                return false;
            }
        });


    }

    /**
     * 更新地图状态显示面板
     */
    public void updateMapState() {
        if (words == null) {
            return;
        }
        if (geoCodeUtil != null && currentPt != null) {
            geoCodeUtil.LatLngToAdress(currentPt);
        }

    }

    public void updateMapState(LatLng currentPt) {
        this.currentPt = currentPt;
        if (MyApp.bdLocation != null) altitude = MyApp.bdLocation.getAltitude();
        if (MyApp.NetWorkConnect) {
            if (geoCodeUtil != null && currentPt != null) {
                geoCodeUtil.LatLngToAdress(currentPt);
            }
        } else if (currentPt != null) {
//            setMarka(currentPt);
            if (currentPt.longitude < 0 || currentPt.latitude < 0 || currentPt.longitude == 4.9E-324 || currentPt.latitude == 4.9E-324) {
//                words.setText("");
                finishAdress = "";
            } else {
                String strInfo = String.format("纬度：%f 经度：%f",
                        currentPt.latitude, currentPt.longitude);
//                words.setText(strInfo);
                finishAdress = strInfo;
            }
        }
    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult result) {
        if (result == null || result.getAddress().length() == 0 || result.error != SearchResult.ERRORNO.NO_ERROR) {
            ToastShow.showShort(this, "抱歉，未能找到结果");
            if (currentPt.longitude < 0 || currentPt.latitude < 0 || currentPt.longitude == 4.9E-324 || currentPt.latitude == 4.9E-324) {
//                words.setText("");
                finishAdress = "";
            } else {
//                setMarka(currentPt);
                String strInfo = String.format("纬度：%f 经度：%f", currentPt.latitude, currentPt.longitude);
//                words.setText(strInfo);
                finishAdress = strInfo;
            }
            return;
        }
//        setMarka(result.getLocation());
    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
        try {
            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR || result.getAddress().length() == 0) {
                ToastShow.showShort(this, "抱歉，未能找到结果");
                if (currentPt.latitude <= 0 || currentPt.longitude <= 0 || currentPt.longitude == 4.9E-324 || currentPt.latitude == 4.9E-324) {
//                    words.setText("");
                    finishAdress = "";
                    return;
                }
//                setMarka(currentPt);
                String strInfo = String.format("纬度：%f 经度：%f", currentPt.latitude, currentPt.longitude);
//                words.setText(strInfo);
                finishAdress = strInfo;
                return;
            }
        } catch (Exception e) {
            return;
        }
//        setMarka(result.getLocation());
//        words.setText(result.getAddress());
        finishAdress = result.getAddress();
    }

    private void setMarka(LatLng point) {
        baidumapstyle.setMarka(point, "");
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(point));//将位置设为中心点
    }

    private void addPoint() {
        point = new ArrayList<>();
        point.addAll(MyApp.explorationList);
        mBaiduMap.clear();
        baidumapstyle.clearmarker_Seconds();
        Map<String, Integer> map = DataUtil.getIconData(0);
        for (Exploration exploration : point) {
            if (exploration.lat != null && exploration.lng != null && exploration.lat.length() > 0 && exploration.lng.length() > 0) {
                LatLng p = new LatLng(Double.parseDouble(exploration.lat), Double.parseDouble(exploration.lng));
                baidumapstyle.addMarka(exploration, getApplicationContext(), p, Integer.parseInt(map.get(exploration.pt_id).toString()));
                if (exploration.before_lat != null && exploration.before_lng != null && exploration.before_lat.length() > 0 && exploration.before_lng.length() > 0) {
                    LatLng p1 = new LatLng(Double.parseDouble(exploration.lat), Double.parseDouble(exploration.lng));
                    LatLng p2 = new LatLng(Double.parseDouble(exploration.before_lat), Double.parseDouble(exploration.before_lng));
                    List<LatLng> points = new ArrayList<LatLng>();
                    points.add(p1);
                    points.add(p2);
                    OverlayOptions ooPolyline = new PolylineOptions().width(10)
                            .color(R.color.red).points(points);
                    mBaiduMap.addOverlay(ooPolyline);
                }
            }
        }
    }

    //添加拉线
    public void addLaXian(View view) {
        int count = laXianList.size() + 1;
        ToastShow.showLong(this, "地图已添加第" + count + "条拉线");
        PointLaXian laXian = new PointLaXian();
        laXian.setLxname(UUID.randomUUID().toString());
        laXian.setLat(currentPt0.latitude);
        laXian.setLng(currentPt0.longitude);
        laXian.setPointID(MyApp.currExploration.getExploration_id());
        laXianList.add(laXian);
        setLaXianOnMap(laXian);
    }
}
